using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Winter.BackEnd.Models.Domain;
using System.Web.UI;
using System.Web.Mvc.Html;
using Winter.BackEnd.Models.Utils;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Xml;
using Winter.BackEnd.Models.DataTypes;

namespace Winter.BackEnd.Controllers
{
    [Authorize]
    public class GroupController : ApplicationController
    {

        #region ActionMethods

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "student"), ObjectFilter(Param = "eventDTO", RootType = typeof(EventDTO))]
        public JsonResult SaveEvent(EventDTO eventDTO)
        {
            var result = new JsonResult();

            Event targetEvent = (Event)eventDTO;

            targetEvent.PersonID = Repository.CurrentUser.Person.ID;

            targetEvent.EventTypeID = 1;

            if (Repository.CurrentUser.Person.Student.Group.GroupSchedules.Count != 0)
            {
                targetEvent.ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID;
            }
            else
            {
                Repository.CurrentUser.Person.Student.Group.GroupSchedules.Add(new GroupSchedule()
                {
                    Schedule = new Schedule() { Year = DateTime.Now }
                });
                targetEvent.ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID;
            }

            Repository.CurrentDataContext.Events.InsertOnSubmit(targetEvent);

            Repository.CurrentDataContext.SubmitChanges();

            #region old
            //var startDate = DateTime.ParseExact(string.Format("{0} {1}", start_date, start_time), "yyyy.MM.dd HH.mm.ss", null);
            //var endDate = DateTime.ParseExact(string.Format("{0} {1}", end_date, end_time), "yyyy.MM.dd HH.mm.ss", null);

            //try
            //{
            //    Repository.CurrentDataContext.Events.InsertOnSubmit(new Event()
            //    {
            //        event_pid = id,
            //        Description = text,
            //        event_length = event_legth,
            //        EventStartTime = startDate,
            //        EventEndTime = endDate,
            //        rec_type = rec_type != "null" ? rec_type : null,
            //        PersonID = 1,
            //        LetureRoom = "2",
            //        EventTypeID = 1,
            //        ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID
            //    });

            //    Repository.CurrentDataContext.SubmitChanges();
            //}
            //catch (Exception ex)
            //{
            //    result.Data = new { errorMessage = ex.Message };
            //}
            #endregion

            return result;
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public JsonResult GetXMLSchedule()
        {
            JsonResult result = new JsonResult();

            int groupID = Repository.CurrentUser.Person.Student.GroupID;

            var events = Repository.GetEventsFroGroup(groupID);
            List<EventDTO> eventsJSON = new List<EventDTO>(); ;

            foreach (var scheduleEvent in events)
            {
                eventsJSON.Add(new EventDTO()
                {
                    end_date = scheduleEvent.EventEndTime.ToString("yyyy.MM.d HH.mm.ss"),
                    start_date = scheduleEvent.EventStartTime.ToString("yyyy.MM.d HH.mm.ss"),
                    custom_data = scheduleEvent.Description,
                    text = scheduleEvent.Description,
                    rec_type = scheduleEvent.rec_type,
                    event_length = scheduleEvent.event_length.HasValue ? scheduleEvent.event_length.ToString() : null
                });
            }

            result.Data = eventsJSON.ToArray();

            #region XML
            //using (XmlWriter xmlWriter = XmlTextWriter.Create(str))
            //{
            //    xmlWriter.WriteStartElement("data");
            //    {
            //        var events = Repository.GetEventsFroGroup(groupID);
            //        if (events != null)
            //        {
            //            foreach (var scheduleEvent in events)
            //            {
            //                xmlWriter.WriteStartElement("event");
            //                xmlWriter.WriteStartAttribute("id");
            //                xmlWriter.WriteValue(scheduleEvent.ID);
            //                xmlWriter.WriteEndAttribute();
            //                {
            //                    xmlWriter.WriteStartElement("id");
            //                    xmlWriter.WriteValue(scheduleEvent.event_pid != null ? scheduleEvent.event_pid : "");
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("start_date");
            //                    xmlWriter.WriteValue(scheduleEvent.EventStartTime.ToString("MM-dd-yyyy HH:mm:ss"));
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("end_date");
            //                    xmlWriter.WriteValue(scheduleEvent.EventEndTime.ToString("MM-dd-yyyy HH:mm:ss"));
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("text");
            //                    xmlWriter.WriteValue(scheduleEvent.Subject != null ? scheduleEvent.Subject.Name : scheduleEvent.Description);
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("details");
            //                    xmlWriter.WriteValue(scheduleEvent.Description);
            //                    xmlWriter.WriteEndElement();
            //                    if (scheduleEvent.event_length.HasValue)
            //                    {
            //                        xmlWriter.WriteStartElement("event_length");
            //                        xmlWriter.WriteValue(scheduleEvent.event_length);
            //                        xmlWriter.WriteEndElement();
            //                    }
            //                    if (!string.IsNullOrEmpty(scheduleEvent.rec_type))
            //                    {
            //                        xmlWriter.WriteStartElement("rec_type");
            //                        xmlWriter.WriteValue(scheduleEvent.rec_type);
            //                        xmlWriter.WriteEndElement();
            //                    }
            //                }
            //                xmlWriter.WriteEndElement();
            //            }
            //        }
            //    }
            //    xmlWriter.WriteEndElement();
            //    xmlWriter.Close();
            //}
            #endregion

            return result;
        }


        public JsonResult GetDataFroCreatingSchedule()
        {
            var result = new JsonResult();
            result.Data = new
            {
                Subjects = from subject in Repository.CurrentDataContext.Subjects
                           select new { Name = subject.Name, ID = subject.ID },
                Buildings = from building in Repository.CurrentDataContext.Builgings
                            select new { Name = building.BuildingName, ID = building.ID },
                Teachers = from teacher in Repository.CurrentDataContext.Teachers
                           select new { Name = teacher.FullName, ID = teacher.ID }

            };
            return result;
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Details()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Create()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();
            ViewData["Days"] = Repository.GetAllDayOfWeekForDropDown();
            ViewData["Subjects"] = Repository.GetAllSubjectsForDropDown();
            ViewData["Teachers"] = Repository.GetAllTeachersForDropDown();

            return View();
        }

        #endregion

        #region HelperMethods

        private string FormatTime(TimeSpan time)
        {
            return string.Format("{0}:{1:D2}", time.Hours, time.Minutes);
        }

        private string GetActionLinkForEvent(int classNumber, int groupID, System.DayOfWeek day)
        {
            //if (Repository.CurrentDataContext.Eventes.Any(c => c.EventNumber == classNumber && c.WorkDay.Schedule.GroupID == groupID && c.WorkDay.DayOfWeek.ID == (int)day))
            //{
            //    var cl = Repository.CurrentDataContext.Eventes.SingleOrDefault(c => c.EventNumber == classNumber && c.WorkDay.Schedule.GroupID == groupID && c.WorkDay.DayOfWeek.ID == (int)day);

            //    return "";
            //    //return (new AjaxHelper(),(IViewDataContainer)this).ActionLink(string.Format("{0}\n{1}\n({2})", cl.Subject.Name, cl.LetureRoom, cl.Teacher.Person.FullName),
            //    //    "GetSubjectDetails", cl.ID.ToString(), new System.Web.Mvc.Ajax.AjaxOptions() { UpdateTargetId = "subjectDetails", OnSuccess = "$('#dialog').dialog();" }, null));

            //}
            return @"<a href=""#"">empty</a>";

        }

        private ActionResult GetSchedule(int groupID)
        {
            //int classesNumber = 6;
            //var group = Repository.GetGroupByID(groupID);
            //ViewData["Title"] = "Schedule for group " + group.Name;

            //ViewData["TimeSpaces"] = new List<string>()
            //        {
            //            "8:30 - 10:05",
            //            "10:25 - 12:00",
            //            "12:20 - 13:55",
            //            "14:15 - 15:50",
            //            "16:10 - 17:45",
            //            "18:05 - 19:40",
            //            "20:00 - 21:35",
            //        };

            //ViewData["EventesAtMonday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Monday, classesNumber);
            //ViewData["EventesAtTuesday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Tuesday, classesNumber);
            //ViewData["EventesAtWednesday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Wednesday, classesNumber);
            //ViewData["EventesAtThursday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Thursday, classesNumber);
            //ViewData["EventesAtFriday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Friday, classesNumber);
            //ViewData["EventesAtSaturday"] =
            //                        Repository.GetGroupEventesForSpecificDay(groupID,
            //                        System.DayOfWeek.Saturday, classesNumber);
            return View();
        }

        #endregion

    }
}
